// 树的遍历之查找所有的兄弟节点
// list为树, id为目标节点的id, key为id匹配的字段
import { CommonStringObjectType } from '@/framework/types/common-data'

export function getBrotherNodes(list: any, id: any, key: any) {
  for (const i in list) {
    if (list[i][key] === id) return list
    if (list[i].children?.length > 0) {
      const node: any = getBrotherNodes(list[i].children, id, key)
      if (node) return node
    }
  }
}

// 树的遍历之查找所有的父节点
// list为树, id为目标节点的id, key为id匹配的字段
export function getAllParentNodes(list: any, id: any, key: any) {
  for (const i in list) {
    if (list[i][key] === id) return [list[i]].filter((v) => v[key] !== id)
    if (list[i].children?.length > 0) {
      const node: any = getAllParentNodes(list[i].children, id, key)
      if (node) return node.concat(list[i]).filter((v: any) => v[key] !== id)
    }
  }
}

export const traverseTreeNodeAttr = (nodeList: any, callback: (object: any) => void) => {
  if (!Array.isArray(nodeList) || !nodeList.length) return
  for (const node of nodeList) {
    callback(node)
    if (node.children && node.children.length > 0) traverseTreeNodeAttr(node.children, callback)
  }
}
